from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination

from django import forms
from django.core.exceptions import ValidationError
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.encrypt import md5

class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ["username", 'password', "confirm_password","depart"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，此字段以后保存到数据库就是什么。
        return confirm

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')

        if username:
            if models.Admin.objects.filter(username=username).exists():
                raise ValidationError("用户名已经存在")

        return cleaned_data

    def __init__(self, *args, request=None, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)

    # 新增以下方法，用于在保存表单数据到模型实例时，设置org_id的值
    # def save(self, commit=True):
    #     instance = super().save(commit=False)
    #     instance.org_id = self.request.session.get('admin_info', {}).get('org_id')
    #     if commit:
    #         instance.save()
    #     return instance


class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username','depart']

    def __init__(self, *args, request=None, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)
        if self.request:
            current_admin_org_id = self.request.session.get('admin_info', {}).get('org_id')
            # 获取当前org_id对应的管理员创建的部门列表
            department_list = models.Department.objects.filter(org_id=current_admin_org_id).values_list('id', 'title')
            self.fields['depart'].choices = department_list
            self.fields['depart'].label_from_instance = lambda obj: obj.title

class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        md5_pwd = md5(pwd)

        # 去数据库校验当前密码和新输入的密码是否一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError("不能与以前的密码相同")

        return md5_pwd

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，此字段以后保存到数据库就是什么。
        return confirm

def admin_list(request):
    """ 管理员列表 """

    # info_dict = request.session["info"]
    # print(info_dict["id"])
    # print(info_dict['name'])
    # 获取当前登录管理员的org_id，假设在session中存储了当前登录管理员的信息
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')

    # 构造搜索
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["username__contains"] = search_data

    # 根据当前登录管理员的org_id和搜索条件去数据库获取
    queryset = models.Admin.objects.filter(org_id=current_admin_org_id, **data_dict)
    # 分页
    page_object = Pagination(request, queryset)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        "search_data": search_data
    }
    return render(request, 'admin_list.html', context)

def admin_add(request):
    """ 添加管理员 """
    title = "新建管理员"
    # 获得当前管理员的org_id
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')

    if request.method == "GET":
        initial_data = {'admin_info': {'org_id': request.session.get('admin_info', {}).get('org_id')}}
        form = AdminModelForm(initial=initial_data)
        return render(request, 'change.html', {'form': form, "title": title})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        depart = form.cleaned_data.get('depart')
        same_name_user = models.Admin.objects.filter(username=username)
        if same_name_user:
            message = "用户名已存在"
            form.add_error('username', message)
            return render(request, 'change.html', {'form': form, "title": title})

        instance = form.save(commit=False)
        instance.org_id = request.session.get('admin_info', {}).get('org_id')
        instance.save()

        return redirect('/admin/list/')


    return render(request, 'change.html', {'form': form, "title": title})

def admin_edit(request, nid):
    """ 编辑管理员 """
    # 对象 / None
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    row_object = models.Admin.objects.filter(id=nid, org_id=current_admin_org_id).first()
    if not row_object:
        # return render(request, 'error.html', {"msg": "数据不存在"})
        return redirect('/admin/list/')

    title = "编辑管理员"
    if request.method == "GET":
        initial_data = {'admin_info': {'org_id': request.session.get('admin_info', {}).get('org_id')}}
        form = AdminEditModelForm(request=request,initial=initial_data, instance=row_object)
        return render(request, 'change.html', {"form": form, "title": title})

    form = AdminEditModelForm(request=request,data=request.POST, instance=row_object)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = models.Admin.objects.filter(id=nid, org_id=current_admin_org_id).first().password
        depart = form.cleaned_data.get('depart')
        same_name_user = models.Admin.objects.filter(username=username)
        if same_name_user:
            message = "用户名已存在"
            form.add_error('username', message)
            return render(request, 'change.html', {'form': form, "title": title})

        instance = form.save(commit=False)
        instance.org_id = request.session.get('admin_info', {}).get('org_id')
        instance.save()

        return redirect('/admin/list/')
    return render(request, 'change.html', {"form": form, "title": title})

def admin_delete(request,nid):
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    models.Admin.objects.filter(id=nid, org_id=current_admin_org_id).delete()
    return redirect('/admin/list/')


def admin_reset(request, nid):
    """ 重置密码 """
    # 对象 / None
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    row_object = models.Admin.objects.filter(id=nid, org_id=current_admin_org_id).first()
    if not row_object:
        return redirect('/admin/list/')

    title = "重置密码 - {}".format(row_object.username)

    if request.method == "GET":
        form = AdminResetModelForm(request=request)
        return render(request, 'change.html', {"form": form, "title": title})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        new_admin = form.save(commit=False)  # 获取到要保存的新管理员对象但暂不保存到数据库
        new_admin.org_id = current_admin_org_id  # 将当前登录管理员的 org_id 设置给新管理员对象的 org_id 字段
        new_admin.save()  # 最后再保存到数据库
        return redirect('/admin/list/')
    return render(request, 'change.html', {"form": form, "title": title})

